import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../models/product_model.dart';
import '../../../providers/product_provider.dart';

class ProductController extends GetxController {
  final ProductProvider productProvider = ProductProvider();
  
  // 可观察变量
  final RxBool isLoading = false.obs;
  final RxBool isRefreshing = false.obs;
  final RxBool isLoadingMore = false.obs;
  final RxBool isSearching = false.obs;
  final RxBool hasMoreData = true.obs;
  final RxList<Product> products = <Product>[].obs;
  final RxList<Product> searchResults = <Product>[].obs;
  
  // 分页参数
  int currentPage = 1;
  final int pageSize = 10;
  
  // 滚动控制器
  late ScrollController scrollController;
  
  @override
  void onInit() {
    super.onInit();
    scrollController = ScrollController();
    scrollController.addListener(_scrollListener);
    fetchProducts();
  }
  
  @override
  void onClose() {
    scrollController.removeListener(_scrollListener);
    scrollController.dispose();
    super.onClose();
  }
  
  // 滚动监听
  void _scrollListener() {
    if (scrollController.position.pixels >= scrollController.position.maxScrollExtent - 200 &&
        !isLoading.value && 
        !isLoadingMore.value && 
        hasMoreData.value) {
      loadMoreProducts();
    }
  }
  
  // 获取产品列表
  Future<void> fetchProducts() async {
    try {
      isLoading.value = true;
      final response = await productProvider.getProductList(
        pageNum: currentPage,
        pageSize: pageSize
      );
      products.assignAll(response.rows);
      
      // 判断是否还有更多数据
      hasMoreData.value = response.rows.length >= pageSize && response.total > products.length;
    } catch (e) {
      Get.snackbar('错误', '获取产品列表失败: $e');
    } finally {
      isLoading.value = false;
      isRefreshing.value = false;
    }
  }
  
  // 刷新产品列表
  Future<void> refreshProducts() async {
    isRefreshing.value = true;
    currentPage = 1;
    hasMoreData.value = true;
    await fetchProducts();
    return;
  }
  
  // 加载更多产品
  Future<void> loadMoreProducts() async {
    if (isLoadingMore.value || !hasMoreData.value) return;
    
    isLoadingMore.value = true;
    currentPage++;
    try {
      final response = await productProvider.getProductList(
        pageNum: currentPage,
        pageSize: pageSize
      );
      
      if (response.rows.isNotEmpty) {
        products.addAll(response.rows);
      }
      
      // 判断是否还有更多数据
      hasMoreData.value = response.rows.length >= pageSize && response.total > products.length;
      
      if (response.rows.isEmpty) {
        hasMoreData.value = false;
      }
    } catch (e) {
      currentPage--; // 恢复页码
      Get.snackbar('错误', '加载更多产品失败: $e');
    } finally {
      isLoadingMore.value = false;
    }
  }
  
  // 搜索产品
  Future<void> searchProducts(String query) async {
    if (query.isEmpty) {
      searchResults.clear();
      return;
    }
    
    try {
      isSearching.value = true;
      // 按产品名称或产品标识码搜索
      final response = await productProvider.getProductList(
        pageNum: 1,
        pageSize: 20,
        productName: query,
      );
      
      // 如果按名称搜索没有结果，尝试按产品标识码搜索
      if (response.rows.isEmpty) {
        final keyResponse = await productProvider.getProductList(
          pageNum: 1,
          pageSize: 20,
          productKey: query,
        );
        searchResults.assignAll(keyResponse.rows);
      } else {
        searchResults.assignAll(response.rows);
      }
    } catch (e) {
      Get.snackbar('错误', '搜索产品失败: $e');
    } finally {
      isSearching.value = false;
    }
  }
  
  // 查看产品详情
  void viewProductDetail(int? productId) {
    if (productId == null) {
      Get.snackbar('错误', '产品ID不能为空');
      return;
    }
    
    // 跳转到产品详情页面
    Get.toNamed('/product/detail', arguments: {'productId': productId});
  }
  
  // 添加新产品
  void addNewProduct() {
    // 跳转到添加产品页面
    // 这里需要实现添加产品页和路由，目前先用snackbar示意
    Get.snackbar('提示', '添加新产品');
    // Get.toNamed('/product/add');
  }
}